package org.jiuling.wecom.base;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.jiuling.local.tools.exception.LocalToolsException;
import org.jiuling.local.tools.verify.ObjectVerify;
import org.jiuling.network.tools.http.request.HttpRequest;
import org.jiuling.network.tools.http.request.enums.RequestMethodEnum;
import org.jiuling.network.tools.http.request.exception.RequestException;
import org.jiuling.network.tools.http.request.factory.HttpRequestFactory;
import org.jiuling.network.tools.http.request.model.HttpRequestParam;
import org.jiuling.wecom.base.enums.WeComApiEnum;
import org.jiuling.wecom.base.model.AccessTokenModel;
import org.jiuling.wecom.config.WeComConfig;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * 授权
 * @author 紫灵
 * @date 2023年04月02日 22时22分30秒
 */
public class Authorization {

    /** 企业微信配置 */
    private final WeComConfig weComConfig;
    private AccessTokenModel accessTokenModel;

    public Authorization(WeComConfig weComConfig) {
        this.weComConfig = weComConfig;
    }

    /**
     * 获取Token
     * @return 访问Toekn模型
     */
    public AccessTokenModel getToken(){
        // 判断当前Token是否过期，如果过期则重新获取Token
        if(verifyAccessTokenExpiresTime()){
            HttpRequestParam httpRequestParam = new HttpRequestParam()
                    .add("corpid",weComConfig.getCorpId())
                    .add("corpsecret",weComConfig.getCorpSecret());
            HttpRequest httpRequest = new HttpRequest();
            try {
                // 获取开启HTTP请求过程
                HttpRequestFactory httpRequestFactory = httpRequest.openHttpRequestFactory(WeComApiEnum.GET_TOKEN.getApi());
                httpRequestFactory.setRequestParam(httpRequestParam);
                httpRequestFactory.setRequestMethod(RequestMethodEnum.GET);
                JSONObject jsonObject = JSON.parseObject(httpRequest.send().getBody());
                // 发送请求并获取Token
                accessTokenModel = AccessTokenModel.builder()
                        .addAccessToken(jsonObject.getString("access_token"))
                        .addExpiresTime(jsonObject.getInteger("expires_in"))
                        .build();
            } catch (RequestException | IOException | LocalToolsException | NoSuchAlgorithmException |
                     KeyManagementException e) {
                throw new RuntimeException(e);
            }
        }
        return accessTokenModel;
    }

    /**
     * 验证访问令牌过期时间
     * @return 是否过期
     */
    private boolean verifyAccessTokenExpiresTime(){
        return ObjectVerify.isNull(accessTokenModel) || accessTokenModel.getExpiresTime().getTime() < new Date().getTime();
    }

}
